<?php

namespace App\JobEntity;

abstract class Entity
{
    /**
     * __get.
     *
     * @author yansongda <me@yansongda.cn>
     *
     * @param $key
     *
     * @throws \ReflectionException
     *
     * @return mixed
     */
    public function __get($key)
    {
        return $this->get($key);
    }

    /**
     * get.
     *
     * @author yansongda <me@yansongda.cn>
     *
     * @param null $key
     * @param null $default
     *
     * @throws \ReflectionException
     *
     * @return mixed|null
     */
    public function get($key = null, $default = null)
    {
        if (is_null($key)) {
            return $this->getArray();
        }

        $method = 'get';
        foreach (explode('_', $key) as $item) {
            $method .= ucfirst($item);
        }

        if (method_exists($this, $method)) {
            return $this->{$method}();
        }

        return $default;
    }

    public function getArray()
    {
        $data = [];
        $reflect = new \ReflectionClass($this);
        $props = $reflect->getProperties();
        foreach ($props as $item) {
            $data[$item->getName()] = $this->{$item->getName()};
        }

        return $data;
    }
}